package com.ytf.core.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ytf.core.common.CacheOperatorApi;
import com.ytf.core.web.pojo.model.RolePermission;
import com.ytf.core.web.mapper.RolePermissionMapper;
import com.ytf.core.web.pojo.vo.RoleVo;
import com.ytf.core.web.service.IRolePermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * <p>
 * 角色权限关联表 服务实现类
 * </p>
 *
 * @author YTF
 * @since 2025-05-20
 */
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements IRolePermissionService {

    @Resource(name = "roleCache")
    private CacheOperatorApi<RoleVo> roleCache;

    @Override
    public Boolean removeByRoleId(Long roleId) {
        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RolePermission::getRoleId,roleId);
        return this.remove(queryWrapper);
    }

    @Override
    public Boolean removeByPermissionId(Long permissionId) {
        List<RolePermission> list = lambdaQuery().eq(RolePermission::getPermissionId, permissionId).list();
        if (list.isEmpty()) {
            return true;
        }
        // 删除角色缓存
        List<String> roleIds = list.stream().map(m -> String.valueOf(m.getRoleId())).toList();
        roleCache.remove(roleIds);

        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RolePermission::getPermissionId,permissionId);
        return this.remove(queryWrapper);
    }

    @Override
    public List<Long> listPermissionIdByRoleId(Long id) {
        return lambdaQuery().eq(RolePermission::getRoleId,id)
                .select(RolePermission::getPermissionId).list().stream().map(RolePermission::getPermissionId).toList();
    }

    @Override
    public Boolean removeByRoleIdAndPermissionId(Long roleId, List<Long> permissionsToRemove) {
        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RolePermission::getRoleId,roleId)
                .in(RolePermission::getPermissionId,permissionsToRemove);
        return this.remove(queryWrapper);
    }

    @Override
    public Boolean existsByPermissionId(Long permissionId) {
        return lambdaQuery().eq(RolePermission::getPermissionId,permissionId).exists();
    }
}
